package com.nd.android.u.ui.widge;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.common.android.utils.DisplayUtil;
import com.nd.android.u.business.db.dao.QuickReplyDao;
import com.nd.android.u.chatInterfaceImpl.ChatInterfaceImpl;
import com.nd.android.u.controller.bean.QuickReply;
import com.nd.android.u.controller.bean.QuickReplyList;
import com.nd.android.u.controller.factory.ChatDaoFactory;
import com.nd.android.u.ui.ChatEntry;
import com.nd.android.u.ui.R;
import com.nd.android.u.ui.activity.chat_relative_quickreply.QuickReplyAcitivty;
import com.nd.android.u.ui.activity.chat_relative_quickreply.QuickReplyAdapter;
import com.product.android.commonInterface.weibo.FlowerMessageInfo;
import com.product.android.utils.SharedPreferenceHelper;

public class PopQuickReply {
	public static final int REPLY_TYPE_CHAT = 0;
	public static final int REPLY_TYPE_ACKNOWLEDGE = 1;
	public static final int REPLY_TYPE_PRESENT = 2;
	private int mReplyType;
	public interface onSwitchToEditListener{
		//在弹窗界面进入快捷回复编辑
		void onSwicthToEdit();
	}
	private onSwitchToEditListener mSwitchToEditListener;
	public interface onItemSelectListener{
		//选中某个快捷回复
		void onItemSelect(String text);
	}
	private onItemSelectListener mItemSelectListener;
	private Context mContext;
	private ListView lvQuickReply;
	private QuickReplyList mReplyList;
	private QuickReplyDao mQuickReplyDao;
	private int mItemHeight;
	private boolean mbIsToEdit=false;
	private QuickReplyAdapter mQuickReplyAdapter;
	private long mFid;
	private String[] mPostQuickReplies;
	private boolean mIsInit=false;		//是否已初始化
	private boolean mIsPopup=false;		//是否是在弹窗界面
	public PopQuickReply(Context context, int type, long fid,boolean isPopup){
		mContext=context;
		this.mReplyType = type;
		this.mFid = fid;
		mIsPopup=isPopup;
	}
	
	public void setListView(ListView lv){
		lvQuickReply=lv;
	}
	
	public void setOnSwitchToEditListener(onSwitchToEditListener listener){
		mSwitchToEditListener=listener;
	}
	
	public void setOnItemSelectListener(onItemSelectListener listener){
		mItemSelectListener=listener;
	}
	
	private void buildWindow(View anchor){
		mIsInit=true;
		getReplyTexts();
		mQuickReplyAdapter=new com.nd.android.u.ui.activity.chat_relative_quickreply.QuickReplyAdapter(mContext,mReplyList);
		lvQuickReply.setAdapter(mQuickReplyAdapter);
		lvQuickReply.setOnItemClickListener(itemClickListener);
		//获取单个item的高度
		mItemHeight=DisplayUtil.dip2px(mContext, QuickReplyAdapter.ITEM_HEIGHT);
		int size=mReplyList.size();
		int h=mItemHeight*size;
		int maxHeight=anchor.getHeight();
		if (!mIsPopup){
			//在聊天界面（非弹窗界面），允许的最大高度为listview的一半
			maxHeight=5*mItemHeight;
		}
		h=Math.min(h, maxHeight);
		//设定宽度为listview的宽度的一半
		//int w=anchor.getWidth()/2;
		// 宽度改为19/20 update by ZXQ
		int w=anchor.getWidth() * 19 / 20;
		RelativeLayout.LayoutParams lp=(LayoutParams) lvQuickReply.getLayoutParams();
		lp.width=w;
		lp.height=h;
		lvQuickReply.setLayoutParams(lp);
	}
	
	public void setQuickReply(String[] replies){
		mPostQuickReplies=replies;
	}
	
	private void getReplyTexts(){
		// 送花答谢快捷回复
		if (mReplyType == REPLY_TYPE_ACKNOWLEDGE) {
			String[] defaults=mContext.getResources().getStringArray(R.array.quick_acknowledge);
			mReplyList=new QuickReplyList();
			for (int i = 0, len = defaults.length; i < len; i++) {
				QuickReply reply = new QuickReply();
				if (defaults[i].contains("XXX")) {
					reply.setText(defaults[i].replaceAll("XXX", ChatInterfaceImpl.INSTANCE.chatCallOtherModel.getUserName(mFid)));
				} else {
					reply.setText(defaults[i]);
				}
				reply.setOrder(i);
				mReplyList.add(reply);
			}
			//  判断是否有设置过送花答谢留言
			FlowerMessageInfo info = ChatEntry.INSTANCE.chatCallOtherModel_UI.getThanksFlowerMessage();
			if (info != null) {
				QuickReply set=new QuickReply();
				set.setText(mContext.getString(R.string.quick_reply_acknowledge));
				mReplyList.add(0, set);
			}
			return;
		}
		if (mPostQuickReplies!=null){
			int size=mPostQuickReplies.length;
			if (size==0){
				mPostQuickReplies=mContext.getResources().getStringArray(R.array.quick_present);
			}
			mReplyList=new QuickReplyList();
			int i=0;
			for (String str : mPostQuickReplies) {
				QuickReply reply=new QuickReply();
				reply.setText(str);
				reply.setOrder(i);
				i++;
				mReplyList.add(reply);
			}
			//  判断是否有设置过送花答谢留言
			FlowerMessageInfo info = ChatEntry.INSTANCE.chatCallOtherModel_UI.getThanksFlowerMessage();
			if (info != null) {
				QuickReply set=new QuickReply();
				set.setText(mContext.getString(R.string.quick_reply_acknowledge));
				mReplyList.add(0, set);
			}
		}else {
			mQuickReplyDao=ChatDaoFactory.getInstance().getQuickReplyDao();
			mReplyList=mQuickReplyDao.getReply();
			String key=SharedPreferenceHelper.HAS_UPDATE_QUICK_REPLY;
			String[] defaults=mContext.getResources().getStringArray(R.array.quick_reply);
			if (mReplyList==null || mReplyList.size()==0){
				mReplyList=new QuickReplyList();
				for (int i=0,len=defaults.length;i<len;i++){
					QuickReply reply=new QuickReply();
					reply.setText(defaults[i]);
					reply.setOrder(i);
					mReplyList.add(reply);
					mQuickReplyDao.insertReply(reply);
				}
				//设置成已更新(数据库里没有数据的时候，直接用的就是新的快捷回复，所以这边设置为已更新)
				SharedPreferenceHelper.getInstance().saveBooleanKey(key, true);
			}else{
				//1.3.7时变更了默认的快捷回复的内容，但是由于之前的版本里已经把默认的快捷回复写到数据库里，因此需要把数据库里的旧的文字也换成新的

			    //XXX 无该需求
			    //				int version=PubFunction.getAppVersionCode(mContext);
//				if (version>53){
//					boolean hasUpdated=SharedPreferenceHelper.getInstance().loadBooleanKey(key, false);
//					if (!hasUpdated){
//						//还未更新默认快捷回复内容，遍历所有的现有快捷回复，只要找到与旧的快捷回复一致内容就强行换成新的。
//						//隐藏风险：可能有用户自己更改了默认快捷回复，但是更改的内容和旧的快捷回复内容一致，就会把用户自己改的也替换掉
//						String[] oldReply=mContext.getResources().getStringArray(R.array.quick_reply);
//						for (QuickReply reply : mReplyList) {
//							for (int i = 0,len=oldReply.length; i < len; i++) {
//								if (reply.getText().equals(oldReply[i])){
//									//内容是旧的，替换成新的，并且更新数据库
//									reply.setText(defaults[i]);
//									mQuickReplyDao.updateReply(reply);
//									break;
//								}
//							}
//						}
//						//设置成已更新（新版本安装后只更新一次快捷回复）
//						SharedPreferenceHelper.getInstance().saveBooleanKey(key, true);
//					}
//				}
			}
			QuickReply set=new QuickReply();
			set.setText(mContext.getString(R.string.quick_reply_set));
			mReplyList.add(set);
		}
	}
	
	public void refresh(){
		if (mbIsToEdit){
			mbIsToEdit=false;
			mIsInit=false;
		}
	}
	
	public void show(View anchor){
		if (!mIsInit){
			buildWindow(anchor);
		}
		lvQuickReply.setVisibility(View.VISIBLE);
	}
	
	public void dismiss(){
		lvQuickReply.setVisibility(View.GONE);
	}
	
	public boolean isShowing(){
		return lvQuickReply.getVisibility()==View.VISIBLE;
	}
	
	private OnItemClickListener itemClickListener=new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// 只有普通聊天的快捷回复才进入快捷回复设置
			if (mReplyType == REPLY_TYPE_CHAT && arg2==mReplyList.size()-1){
				if (mSwitchToEditListener!=null){
					mSwitchToEditListener.onSwicthToEdit();
				}else{
					//未专门设置一个监听，直接进入快捷回复编辑界面
					Intent intent=new Intent(mContext, QuickReplyAcitivty.class);
					((Activity)mContext).startActivity(intent);
					mbIsToEdit=true;	
				}
			} else {
				if (mItemSelectListener != null) {
					mItemSelectListener.onItemSelect(mReplyList.get(arg2).getText());
				}
			}
			dismiss();
		}
	};

	/**
	 * mReplyType
	 *
	 * @return  the mReplyType
	 * @since   CodingExample Ver 1.0
	 */
	public int getmReplyType() {
		return mReplyType;
	}

	/**
	 * mReplyType
	 *
	 * @param   mReplyType    the mReplyType to set
	 * @since   CodingExample Ver 1.0
	 */
	public void setmReplyType(int mReplyType) {
		this.mReplyType = mReplyType;
	}
}
